<template>


	<!-- A仓 -->
	<view style="min-height: 800px;">


		<scroll-view id="nav-bar" scroll-x class="nav margin-top">
			<view class="flex text-center">
				<view class="cu-item flex-sub" :id="'tab'+index" v-for="(item,index) in tabBars" :key="item.id" :class="index==tabCurrentIndex?'text-white cur':''"
				 @tap="changeTab(index)">
					{{item.name}}
				</view>
			</view>
		</scroll-view>
		<!-- 下拉刷新组件 -->
		<!-- <mix-pulldown-refresh ref="mixPulldownRefresh" class="panel-content" :top="90" @refresh="onPulldownReresh"
		 @setEnableScroll="setEnableScroll"> -->
		<!-- 内容部分 -->
		<swiper id="swiper" class="swiper-box" :duration="300" :current="tabCurrentIndex" @change="changeTab">
			<swiper-item v-for="tabItem in tabBars" :key="tabItem.id">

				<scroll-view class="panel-scroll-box" scroll-y="true" @scrolltolower="loadMore">
					<!-- tab3 交易 -->
					<template v-if="tabItem.id==1">
						<view class="cu-list menu-avatar" v-for="(item, index) in tabItem.newsList" :key="index">
							<view class="cu-item">

								<view class="cu-tag trade_1" :class="item.side=='long' ? 'bg-yellow' : 'bg-red'">{{order_direction[item.side]}}</view>
								<view class="content">
									<view>{{item.symbol}}
 
										<view class="cu-tag bg-yellow margin-left-sm" :class="item.side=='long' ? 'bg-yellow' : 'bg-red'">{{item.leverage}}X</view>
									</view>
									<view class="text-gray text-sm flex">
										<view class="text-cut">
											{{item.createTime}}
										</view>
									</view>
								</view>
								<view class=" ">
									<button class="cu-btn round line-yellow" @tap="closeorder(item)" :loading="loading">平仓</button>
								</view>
							</view>
							<view class="flex cu-item" style="position: inherit;">

								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit ">{{item.liquidationPrice}}</view>
									<text class="text-gray ">强平价格</text>
								</view>
								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit ">{{item.markPrice}}</view>
									<text class="text-gray ">标记价格</text>
								</view>
								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit ">{{item.avgPrice}}</view>
									<text class="text-gray ">开仓均价</text>
								</view>

							</view>
							<view class="flex cu-item" style="position: inherit;margin-top: -10px;">

								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit ">{{item.availableQuantity}}/{{item.quantity}}</view>
									<text class="text-gray ">可平仓数量</text>
								</view>
								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit " :class="item.unrealisedPnl>0 ? 'text-yellow' : 'text-red'">{{item.roe}}%</view>
									<text class="text-gray ">收益率</text>
								</view>
								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit " :class="item.unrealisedPnl>0 ? 'text-yellow' : 'text-red'">{{item.unrealisedPnl}}</view>
									<text class="text-gray ">未实现盈亏</text>
								</view>
							</view>
							<view class="flex cu-item" style="position: inherit;margin-top: -10px;">
							
								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit ">{{item.positionMargin}}</view>
									<text class="text-gray ">保证金</text>
								</view>
								<!-- <view class="flex-sub  margin-xs radius text-center">
									<view class="tit ">{{item.markPrice}}</view>
									<text class="text-gray ">标记价格</text>
								</view>
								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit ">{{item.avgPrice}}</view>
									<text class="text-gray ">开仓均价</text>
								</view> -->
							
							</view>
							<view v-show="modalName=='ping'+item.orderId">
								<view class="cu-form-group t-t1">
									<view class="title">平仓价格</view>
									<input type="number" v-model="pingprice" placeholder="请输入平仓价格"></input>
									<text class="text-gray margin-right-sm">USDT</text>
									<!-- <text @tap="allin">{{i18n.cash.allin}}</text> -->
								</view>
								<view class="flex padding-xs bg-black">
									<view class="flex-sub padding-xs">
										<button class="cu-btn  botton-b" @tap="hideModal">{{i18n.contract.bt5}}</button>
									</view>
									<view class="flex-sub padding-xs">
										<button class="cu-btn bg-yellow botton-b" @tap="closeorder(item)">{{i18n.contract.bt6}}</button>
									</view>
								</view>
							</view>

						</view>
					</template>

					<template v-if="tabItem.id==2">
						<view class="cu-list menu-avatar" v-for="(item, index) in tabItem.newsList" :key="index">
							<view class="cu-item">

								<view class="cu-tag trade_1" :class="item.direction=='openLong' ? 'bg-yellow' : 'bg-red'">{{order_direction[item.direction]}}</view>
								<view class="content">
									<view>{{item.symbol}}

										<view class="cu-tag bg-yellow margin-left-sm round" :class="item.direction=='openLong' ? 'bg-yellow' : 'bg-red'">{{item.leverage}}X</view>
									</view>
									<view class="text-gray text-sm flex">
										<view class="text-cut">
											{{item.orderTime}}
										</view>
									</view>
								</view>
								<view class=" ">
									<!-- <button class="cu-btn bg-yellow round sm"  >平仓</button> -->
									<button class="cu-btn bg-yellow round" @tap="cancle(item)" v-if="item.status=='new'" :loading="loading">撤单</button>
								</view>
							</view>

							<view class="flex cu-item" style="position: inherit;">

								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit">{{item.filledQuantity}}/{{item.quantity}}</view>
									<text class="text-gray ">成交量（张）</text>
								</view>
								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit">{{item.orderPrice}}</view>
									<text class="text-gray ">订单价格</text>
								</view>

								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit ">{{order_state[item.status]}}</view>
									<text class="text-gray ">状态</text>
								</view>
							</view>
						</view>
					</template>

					<template v-if="tabItem.id==3">
						<view class="cu-list menu-avatar" v-for="(item, index) in tabItem.newsList" :key="index">
							<view class="cu-item">

								<view class="cu-tag trade_1" :class="item.direction=='openLong' ? 'bg-yellow' : 'bg-red'">{{order_direction[item.direction]}}</view>
								<view class="content">
									<view>{{item.symbol}}

										<view class="cu-tag bg-yellow margin-left-sm round" :class="item.direction=='openLong' ? 'bg-yellow' : 'bg-red'">{{item.leverage}}X</view>
									</view>
									<view class="text-gray text-sm flex">
										<view class="text-cut">
											{{item.orderTime}}
										</view>
									</view>
								</view>
								<view class=" ">

									<button class="cu-btn bg-yellow round" @tap="cancle(item)" v-if="item.status=='new'" :loading="loading">撤单</button>
								</view>
							</view>

							<view class="flex cu-item" style="position: inherit;">

								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit">{{item.filledQuantity}}/{{item.quantity}}</view>
									<text class="text-gray ">成交量（张）</text>
								</view>
								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit">{{item.orderPrice}}</view>
									<text class="text-gray ">订单价格</text>
								</view>

								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit ">{{order_state[item.status]}}</view>
									<text class="text-gray ">状态</text>
								</view>
							</view>
							<view class="flex cu-item" style="position: inherit;margin-top: -10px;">

								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit " :class="item.profit>=0 ? 'text-yellow' : 'text-red'">{{item.profit}}</view>
									<text class="text-gray ">盈亏</text>
								</view>
								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit">{{item.fee}}</view>
									<text class="text-gray ">手续费</text>
								</view>
								<!-- <view class="flex-sub  margin-xs radius text-center">
									<view class="tit text-yellow">{{item.profit}}</view>
									<text class="text-gray ">盈亏</text>
								</view> -->
							</view>




						</view>
					</template>

					<template v-if="tabItem.id==4">
						<view class="cu-list menu-avatar" v-for="(item, index) in tabItem.newsList" :key="index">
							<view class="cu-item">

								<view class="cu-tag trade_1   " :class="item.rise_fall=='1' ? 'bg-yellow' : 'bg-red'">{{item.rise_fall=='1' ? '平多' : '平空'}}</view>
								<view class="content">
									<view>{{item.product_id}}

										<view class="cu-tag bg-yellow margin-left-sm round">{{item.shou}}X</view>
									</view>
									<view class="text-gray text-sm flex">
										<view class="text-cut">
											{{item.time_text}}
										</view>
									</view>
								</view>
							</view>

							<view class="flex cu-item" style="position: inherit;margin-top: -10px;">

								
								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit " :class="item.profit>=0 ? 'text-yellow' : 'text-red'">{{item.profit}}</view>
									<text class="text-gray " >A仓盈亏</text>
								</view>
								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit " :class="item.profit>=0 ? 'text-red' : 'text-yellow'">{{item.profit>0 ? -item.profit*0.61 : Math.abs(item.profit)}}</view>
									<text class="text-gray ">B仓盈亏</text>
								</view>
								<view class="flex-sub  margin-xs radius text-center">
									<view class="tit text-yellow">{{item.profit>0 ? Math.round(item.profit*0.39*10000)/10000  : 0}}</view>
									<text class="text-gray ">对冲收益</text>
								</view>
							</view>


						</view>
					</template>
					<view class="" style="height: 50px;"></view>

					<mix-load-more :status="tabItem.loadMoreStatus"></mix-load-more>
				</scroll-view>
			</swiper-item>
		</swiper>
		<!-- </mix-pulldown-refresh> -->
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex'
	// import mixPulldownRefresh from '@/components/mix-pulldown-refresh/mix-pulldown-refresh';
	import mixLoadMore from '@/components/mix-load-more/mix-load-more';
	import json from '@/json'
	let windowWidth = 0,
		scrollTimer = false,
		tabBar;
	export default {
		components: {
			// mixPulldownRefresh,
			mixLoadMore
		},
		props: {
			symbol: {
				type: String,
				default: () => {
					return ''
				}
			},
			buyname: {
				type: String,
				default: () => {
					return ''
				}
			},
			salename: {
				type: String,
				default: () => {
					return ''
				}
			},
		},
		data() {
			return {
				tabCurrentIndex: 0, //当前选项卡索引
				scrollLeft: 0, //顶部选项卡左滑距离
				enableScroll: true,
				tabBars: [],
				category_id: 0,
				TabCur: 0, //当前选项卡索引 
				order_state: {
					'new': '挂单中',
					'filled': '完全成交',
					'canceled': '完全撤单',
					'partiallyFilled': '部分撤单'
				},
				order_direction: {
					'openLong': '开多',
					'openShort': '开空',
					'closeLong': '平多',
					'closeShort': '平空',
					'long': '开多',
					'short': '开空',
				},
				loading: false,
				modalName: null,
				pingprice: '',
			}
		},
		computed: {
			...mapState({
				userinfo: state => state.user.userinfo,
				myconfig: state => state.user.myconfig
			}),
			i18n() {
				return this.$t('message');
			}
		},
		mounted() {
			// console.log('aaaaaaaaaa')
			// 获取屏幕宽度
			windowWidth = uni.getSystemInfoSync().windowWidth;
			this.loadTabbars();
		},
		destroyed() {
			console.log('destroyed')
			clearInterval(this.Timer);
		},
		methods: {
			...mapActions(['getUserinfo']),
			Timer() {},
			setTimer() {
				clearInterval(this.Timer);
				this.Timer = setInterval(() => {
					// var timestamp = Date.parse(new Date());
					// console.log(this.tabBars[0].newsList.length)
					if (this.tabCurrentIndex != 2) {
						this.loadNewsList('refresh');
					}
				}, 3000)
			},
			closetimer() {
				clearInterval(this.Timer);
			},
			//获取分类
			loadTabbars() {
				// console.log('当前持仓')
				let tabList = [{
					name: '当前持仓',
					id: '1',
					uri: 'Contract2.getPosition'
				}, {
					name: '当前委托',
					id: '2',
					uri: 'Contract2.openOrdersByPage'
				}, {
					name: '历史持仓',
					id: '3',
					uri: 'Contract2.closedOrdersByPage'
				}, {
					name: '双仓盈亏',
					id: '4',
					uri: 'Follow.getleadertrade'
				}, ];
				tabList.forEach(item => {
					item.newsList = [];
					item.loadMoreStatus = 0; //加载更多 0加载前，1加载中，2没有更多了
					item.refreshing = 0;
					item.page = 1;
				})
				this.tabBars = tabList;
				// this.loadNewsList('add');
				// this.setTimer();
			},
			//下拉刷新
			onPulldownReresh() {
				this.loadNewsList('refresh');
			},
			//上滑加载
			loadMore() {
				this.loadNewsList('add');
			},
			//设置scroll-view是否允许滚动，在小程序里下拉刷新时避免列表可以滑动
			setEnableScroll(enable) {
				if (this.enableScroll !== enable) {
					this.enableScroll = enable;
				}
			},
			//列表
			loadNewsList(type) {
				// console.log(this.tabCurrentIndex)
				// console.log(type)
				let tabItem = this.tabBars[this.tabCurrentIndex];

				//type add 加载更多 refresh下拉刷新
				if (type === 'add') {
					if (tabItem.loadMoreStatus === 2) {
						return;
					}
					tabItem.loadMoreStatus = 1;
				}
				// #ifdef APP-PLUS
				else if (type === 'refresh') {
					tabItem.refreshing = true;
				}
				// #endif

				if (type === 'refresh') {
					tabItem.page = 1;
				}
				// 请求数据
				let send = {
					symbol: this.symbol + '-SWAP',
					page: tabItem.page
				};
				if (tabItem.id == 4) {
					send.user_id=this.userinfo.id
					this.$http.post(tabItem.uri, send).then(res => {
						console.log(res)
						let list = res.data.data;
						if (type === 'refresh') {
							tabItem.newsList = []; //刷新前清空数组
							//下拉刷新 关闭刷新动画
							this.$refs.mixPulldownRefresh && this.$refs.mixPulldownRefresh.endPulldownRefresh();
							// #ifdef APP-PLUS
							tabItem.refreshing = false;
							// #endif
							tabItem.loadMoreStatus = 0;
						}
						list.forEach(item => {
							// item.id = parseInt(Math.random() * 10000);
							tabItem.newsList.push(item);
						})

						// tabItem.loadMoreStatus = res.data.current_page >= res.data.last_page ? 2 : 0;
						tabItem.loadMoreStatus = 2;
						tabItem.page += 1;
					}).catch(e => {
						tabItem.loadMoreStatus = 2;
					})

				} else {
					this.$http.post(tabItem.uri, send).then(res => {
						// console.log(res); 
						if (res.code == 1) {
							uni.request({
								url: this.$host + res.data.url,
								data: {},
								header: res.data.head,
								timeout: 15000,
								success: (e) => {
									// console.log(e);

									if (e.data.code == 200) {
										let list = e.data.data.reverse();
										// fffffffffffffff
										let tt = list.filter((value) => {
											if (value.status == 'filled') {
												return value
											}
										})
										console.log(tt.length)
										if (tt.length > 0) {
											this.$http.post('Contract2.hand', {
												data: tt
											}).then(res2 => {
												console.log('jjj', res2)
											})
										}
										// fffffffffffffff
										if (type === 'refresh') {
											tabItem.newsList = []; //刷新前清空数组
											//下拉刷新 关闭刷新动画
											this.$refs.mixPulldownRefresh && this.$refs.mixPulldownRefresh.endPulldownRefresh();
											// #ifdef APP-PLUS
											tabItem.refreshing = false;
											// #endif
											tabItem.loadMoreStatus = 0;
										}
										list.forEach(item => {
											// item.id = parseInt(Math.random() * 10000);
											tabItem.newsList.push(item);
										})

										// tabItem.loadMoreStatus = res.data.current_page >= res.data.last_page ? 2 : 0;
										tabItem.loadMoreStatus = 2;
										tabItem.page += 1;
									}
								}
							});
						}
					}).catch(e => {
						tabItem.loadMoreStatus = 2;
					})
				}  

			},
			cancle(item) {
				//撤单
				// this.$http.post('Contract2.cancle', {
				// 	id: item.orderId
				// }).then(res => {
				// 	console.log(res)
				// 	if (res.data != null && res.data.code == 200) {
				// 		this.$api.msg(res.msg)
				// 		this.loadNewsList('refresh');
				// 	} else {
				// 		this.$api.msg('请稍后再试')
				// 	}  
				// })
				let send = {
					id: item.orderId
				}
				this.$http.post('Contract2.cancle', send).then(res => {
					uni.showLoading({
						title: 'loading'
					});
					this.loading = true
					if (res.code == 1) {
						setTimeout(() => {
							uni.hideLoading();
							this.loading = false
						}, 2000)
						uni.request({
							url: this.$host + res.data.url,
							data: {
								orderId: item.orderId
							},
							header: res.data.head,
							method: 'POST',
							success: (e) => {
								// console.log(e.data);
								// console.log(JSON.stringify(e.data));
								uni.showToast({
									title: this.i18n.popup.success
								})
								this.loadNewsList('refresh');
								// if (e.data.code == 200) {
								// 	this.account = e.data.data
								// }
							},
							complete: (e) => {
								uni.hideLoading();
								this.loading = false
							}
						});
					}
				})

			},
			showping(item) {
				this.showModal('ping' + item.orderId)
				return 1
			},
			closeorder(item) {
				// if(!this.pingprice || this.pingprice<=0){
				// 	this.$api.msg('请输入平仓价格')
				// }
				// item.pingprice=this.pingprice
				//平仓
				this.$http.post('Contract2.unwind', item).then(res => {

					if (res.code == 1) {
						uni.showLoading({
							title: 'loading'
						});
						this.loading = true
						uni.request({
							url: this.$host + res.data.url,
							data: res.data.data,
							header: res.data.head,
							method: 'POST',
							success: (e) => {
								uni.hideLoading();
								this.loading = false
								// console.log(e.data);
								// console.log(JSON.stringify(e.data));
								if (e.data.code == 200) {
									uni.showToast({
										title: this.i18n.popup.success
									})
									this.loadNewsList('refresh');
									this.hideModal()
								} else {
									this.$api.msg(e.data.message)
								}
							},
							complete: (e) => {
								uni.hideLoading();
								this.loading = false
							}
						});
					}
				})
				// this.$http.post('Contract2.unwind', item).then(res => {
				// 	console.log(res)
				// 	if (res.data != null && res.data.code == 200) {
				// 		this.$api.msg(res.msg)
				// 		this.loadNewsList('refresh');
				// 	} else {
				// 		this.$api.msg('请稍后再试')
				// 	} 
				// })

			},
			showModal(value) {
				this.modalName = value
			},
			hideModal(e) {
				this.modalName = null
			},
			//tab切换
			async changeTab(e) {

				if (scrollTimer) {
					//多次切换只执行最后一次
					clearTimeout(scrollTimer);
					scrollTimer = false;
				}
				let index = e;
				//e=number为点击切换，e=object为swiper滑动切换
				if (typeof e === 'object') {
					index = e.detail.current
				}
				if (typeof tabBar !== 'object') {
					tabBar = await this.getElSize("nav-bar")
				}
				//计算宽度相关
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0;
				let nowWidth = 0;
				//获取可滑动总宽度
				for (let i = 0; i <= index; i++) {
					let result = await this.getElSize('tab' + i);
					width += result.width;
					if (i === index) {
						nowWidth = result.width;
					}
				}
				if (typeof e === 'number') {
					//点击切换时先切换再滚动tabbar，避免同时切换视觉错位
					this.tabCurrentIndex = index;
				}
				//延迟300ms,等待swiper动画结束再修改tabbar
				scrollTimer = setTimeout(() => {
					if (width - nowWidth / 2 > windowWidth / 2) {
						//如果当前项越过中心点，将其放在屏幕中心
						this.scrollLeft = width - nowWidth / 2 - windowWidth / 2;
					} else {
						this.scrollLeft = 0;
					}
					if (typeof e === 'object') {
						this.tabCurrentIndex = index;
					}
					this.tabCurrentIndex = index;

					//第一次切换tab，动画结束后需要加载数据
					let tabItem = this.tabBars[this.tabCurrentIndex];
					// console.log(tabItem.newsList.length)
					// if (tabItem.newsList.length == 0) {
					// 	this.loadNewsList('refresh');
					// } else {
					// 	tabItem.loaded = true;
					// }
					// if (this.tabCurrentIndex !== 0 && tabItem.loaded !== true) {
					// 	this.loadNewsList('add');
					// 	tabItem.loaded = true;
					// }
					this.loadNewsList('refresh');
					this.setTimer()
				}, 300)

			},
			//获得元素的size
			getElSize(id) {
				return new Promise((res, rej) => {
					let el = uni.createSelectorQuery().select('#' + id);
					el.fields({
						size: true,
						scrollOffset: true,
						rect: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
			// tabSelect(e) {
			// 	this.tabCurrentIndex = e.currentTarget.dataset.id;
			// 	this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60
			// }
		}
	}
</script>

<style scoped>
	.cu-card .title {
		width: 28%;
	}

	.cu-card .title2 {
		width: 70px;
	}

	.trade_1 {
		position: absolute;
		left: 18px;
	}

	.tit {
		font-weight: 600;
		font-size: 18px;
	}

	.row {
		display: inline;
	}

	.bai {
		padding: 6px 12px;
		border-radius: 8px;
	}

	.nowrap {
		white-space: nowrap;
	}

	.cu-list {
		margin-top: 2px;
	}

	.cu-list.grid.no-border {
		padding: 3px 17px;
	}

	.nav .cu-item {
		border: none;
	}


	.swiper-box {
		min-height: 800px;
	}

	.panel-scroll-box {
		height: 100%;

		.panel-item {
			background: #fff;
			padding: 30px 0;
			border-bottom: 2px solid #000;
		}
	}

	.botton-b {
		width: 100%;
		height: 38px;
		font-size: 14px;
		font-family: PingFang SC;
		font-weight: bold;
	}
</style>
